<template>
<div class='base-menu'>
  <unfold>
    <template v-slot:tree-list>
      <div class="left box full-height">
        <!-- header -->
        <div class="box-header bg-primary text-white text-weight-regular">
          <q-icon name="iconfont icontubiao-57" color="white" class="q-mr-sm" />
          <span class="head-title vertical-middle user-select-none">企业</span>
          <q-space></q-space>
          <q-input color="teal" outlined dense bg-color="white" v-model="companyName"
                   style="width: 140px;" @keyup.enter="getCompanyList">
            <template v-slot:append>
              <q-btn @click="getCompanyList" flat round dense icon="iconfont icontubiao-21" size="11px" style="margin-right:-10px"></q-btn>
            </template>
          </q-input>
        </div>

        <!-- 列表 -->
        <q-scroll-area class="box-content bg-white" :thumb-style="CommonConfig.thumbStyle">
          <q-list style="min-width: 100px;">
            <div v-for="company in companyList" :key="company.id">
              <q-item
                class="role-item"
                :active="selectedCompany.id === company.id"
                active-class="activated"
                @click="onCompanyClick(company)"
                clickable
                v-ripple
              >
                <q-item-section>{{ company.name }}</q-item-section>
              </q-item>
              <q-separator />
            </div>
          </q-list>
        </q-scroll-area>
      </div>
    </template>
    <template v-slot:content>
      <div class="right box">
        <div class="relative-position full-height box-content">
          <q-toolbar class="tab">
            <q-tabs class="tab"
                    v-model="tab"
                    shrink stretch dense
                    inline-label
                    align="left" @input="changeTab"
                    active-color="primary"
                    indicator-color="primary"
            >
              <q-tab name="pc" icon="iconfont icontubiao-30" label="PC 端" />
              <q-tab name="mobile" icon="iconfont icontubiao-1" label="手机端" />
              <q-tab name="pad" icon="iconfont icontubiao-32" label="工位 Pad" />
              <!--      <q-tab name="board" icon="iconfont icontubiao-31" label="现场看板" />-->
            </q-tabs>
            <q-space></q-space>
            <q-btn :label="isEdit?'保存':'修改'" color="primary" @click="save()" :loading="saveLoading" />
          </q-toolbar>
          <q-separator class="line"/>
          <q-tab-panels class="tab-panel" v-model="tab" :keep-alive="true">
            <q-tab-panel name="pc">
              <q-table
                :data="dataPC" :columns="columns" :loading="pcLoading"
                row-key="value" class="scroll myTable-line"
                hide-bottom :pagination="{rowsPerPage: 0}"
                no-data-label="暂无数据">
                <template v-slot:body="props">
                  <transition name="fade">
                    <q-tr :props="props" v-show="props.row.show">
                      <q-td key="name" :props="props" :style="{'padding-left': props.row.level*16+14+'px', 'width': '30%'}">
                        <q-btn :class="{'invisible': props.row.childrenCount===0}"
                               dense round flat
                               :icon="props.row.expand ? 'iconfont icontubiao-40' : 'iconfont icontubiao-43'"
                               @click="toggleChildren(props.row)" />
                        {{ props.row.desc }}
                      </q-td>
                      <q-td key="type" :props="props">{{ type[props.row.type] }}</q-td>
                      <q-td key="parentName" :props="props">{{ props.row.parentName }}</q-td>
                      <q-td key="operate" :props="props" style="width: 100px">
                        <q-toggle @input="changeToggle(props.row, $event)" v-model="idsPC[props.row.value]" :disable="!isEdit" />
                      </q-td>
                    </q-tr>
                  </transition>
                </template>
              </q-table>
            </q-tab-panel>
            <q-tab-panel name="mobile">
              <q-table
                :data="dataPhone" :columns="columns" :loading="phoneLoading"
                row-key="value" class="scroll myTable-line"
                hide-bottom :pagination="{rowsPerPage: 0}"
                no-data-label="暂无数据">
                <template v-slot:body="props">
                  <transition name="fade">
                    <q-tr :props="props" v-show="props.row.show">
                      <q-td key="name" :props="props" :style="{'padding-left': props.row.level*16+14+'px', 'width': '30%'}">
                        <q-btn :class="{'invisible': props.row.childrenCount===0}"
                               dense round flat
                               :icon="props.row.expand ? 'iconfont icontubiao-40' : 'iconfont icontubiao-43'"
                               @click="toggleChildren(props.row)" />
                        {{ props.row.desc }}
                      </q-td>
                      <q-td key="type" :props="props">{{ type[props.row.type]}}</q-td>
                      <q-td key="parentName" :props="props">{{ props.row.parentName }}</q-td>
                      <q-td key="operate" :props="props" style="width: 100px">
                        <q-toggle @input="changeToggle(props.row, $event)" v-model="idsPhone[props.row.value]" :disable="!isEdit" />
                      </q-td>
                    </q-tr>
                  </transition>
                </template>
              </q-table>
            </q-tab-panel>
            <q-tab-panel name="pad">
              <q-table
                :data="dataPad" :columns="columns" :loading="padLoading"
                row-key="value" class="scroll myTable-line"
                hide-bottom :pagination="{rowsPerPage: 0}"
                no-data-label="暂无数据">
                <template v-slot:body="props">
                  <transition name="fade">
                    <q-tr :props="props" v-show="props.row.show">
                      <q-td key="name" :props="props" :style="{'padding-left': props.row.level*16+14+'px', 'width': '30%'}">
                        <q-btn :class="{'invisible': props.row.childrenCount===0}"
                               dense round flat
                               :icon="props.row.expand ? 'iconfont icontubiao-40' : 'iconfont icontubiao-43'"
                               @click="toggleChildren(props.row)" />
                        {{ props.row.name }}
                      </q-td>
                      <q-td key="type" :props="props">{{ type[props.row.type] }}</q-td>
                      <q-td key="parentName" :props="props">{{ props.row.parentName }}</q-td>
                      <q-td key="operate" :props="props" style="width: 100px">
                        <q-toggle @input="changeToggle(props.row, $event)" v-model="idsPad[props.row.value]" :disable="!isEdit" />
                      </q-td>
                    </q-tr>
                  </transition>
                </template>
              </q-table>
            </q-tab-panel>
          </q-tab-panels>
        </div>
      </div>
    </template>
  </unfold>
</div>
</template>

<script>
import Unfold from 'src/components/unfold'
import { getCompany } from '../../boot/bms/box-gov'
export default {
  data () {
    return {
      companyName: '', // 企业搜索值
      // 公司
      companyList: [],
      // 选择的企业
      selectedCompany: {
        id: null,
        name: null
      },
      tab: 'pc', // pc|mobile|pad|board
      // 表格数据
      data: [], // PC端列表数据
      dataPC: [], // PC端列表数据
      dataPhone: [], // 手机端列表数据
      dataPad: [], // 工位PAD列表数据
      dataBoard: [], // 现场看板列表数据
      // 表格加载
      pcLoading: false,
      phoneLoading: false,
      padLoading: false,
      boardLoading: false,
      // 选中id数据
      idsPC: {}, // PC选中的数据
      idsPhone: {}, // Phone选中的数据
      idsPad: {}, // Pad选中的数据
      idsBoard: {}, // Board选中的数据
      // 列表头部
      columns: [
        { name: 'name', align: 'left', label: '名称', field: 'sodium' },
        { name: 'type', align: 'center', label: '类型', field: 'carbs' },
        { name: 'parentName', align: 'center', label: '上级菜单', field: 'protein' },
        { name: 'operate', align: 'center', label: '权限', field: 'sodium' }
      ],
      isEdit: false, // 是否编辑状态
      saveLoading: false, // 保存中
      // 菜单类型
      types: [
        { label: '目录', value: 0 },
        { label: '菜单', value: 1 },
        { label: '按钮', value: 2 }
      ],
      type: {
        'MENU_LEVEL_ONE': '目录',
        'PAGE': '菜单',
        'BUTTON': '按钮'
      }
    }
  },
  created () {
    this.getCompanyList()
    this.getMenuList()
  },
  methods: {
    // 获取企业列表
    getCompanyList () {
      let info = {
        name: this.companyName
      }
      // 获取企业列表
      getCompany(info).then((res) => {
        this.companyList = res.data
        if (this.companyList.length > 0) {
          this.selectedCompany = {
            id: this.companyList[0].id,
            name: this.companyList[0].name
          }
          // this.getDeviceByName()
        }
      })
    },
    // 切换tab
    changeTab (value) {
      this.tab = value
      this.getMenuList()
    },
    // 获取数据列表
    getMenuList () {
      let menulist = Object.entries(this.Enums.SYS_PERMISSION)
        .filter(entry => (entry[1].type === 'PAGE' || entry[1].type === 'MENU_LEVEL_ONE'))
        .map(item => item[1])
      this.setData(this.initInfo(menulist))
      // this.setLoading(true)
    },
    // 给数据添加show、expand、isFirst、isLast、 index属性
    initInfo (data) {
      const curData = this.getCurData()
      let info, ids = {}
      if (curData.length === 0) {
        info = data.map((item, index) => {
          // const isLast = index === data.length - 1 ||
          //   (index !== 0 && item.parentId + '' !== '0' && item.parentId === data[index - 1].parentId && item.parentId !== data[index + 1].parentId) ||
          //   (index !== 0 && data[index - 1].value + '' === item.parentId + '' && data[index - 1].childrenCount === 1)
          // 找寻子级数量
          let children
          if (item.parentId === null) {
            children = data.filter(child => child.parentId === item.value)
          }
          ids[item.value] = false
          return {
            ...item,
            show: true,
            expand: true,
            index,
            childrenCount: item.parentId === null ? children.length : 0
          }
        })
      } else {
        info = data.map((item, index) => {
          let tableItem = curData.find(f => {
            return Number(f.value) === Number(item.value)
          })
          // const isLast = index === data.length - 1 ||
          //   (index !== 0 && item.parentId === data[index - 1].parentId && item.parentId !== data[index + 1].parentId) ||
          //   (index !== 0 && data[index - 1].value + '' === item.parentId + '' && data[index - 1].childrenCount === 1)
          // 找寻子级数量
          let children
          if (item.parentId === null) {
            children = data.filter(child => child.parentId === item.value)
          }
          ids[item.value] = false
          return {
            ...item,
            show: tableItem ? tableItem.show : true,
            expand: tableItem ? tableItem.expand : true,
            // isFirst: index === 0 || item.parentId + '' === data[index - 1].value + '',
            // isLast: isLast,
            index,
            childrenCount: item.parentId === null ? children.length : 0
          }
        })
      }
      // // 找到外层的最后一个
      // if (data[data.length - 1].parentId + '' !== '0') {
      //   let lastIds = this.findLast(data[data.length - 1].parentId, data)
      //   lastIds.forEach(item => {
      //     let dataItem = info.find(child => child.value + '' === item + '')
      //     dataItem.isLast = true
      //   })
      // }
      this.setIds(ids)
      return info
    },
    // 找最后一个
    findLast (lastParentId, data) {
      let lastItem = data.find(item => {
        return item.value + '' === lastParentId + ''
      })
      let lastIds = [lastItem.value]
      if (lastItem.parentId + '' !== '0') {
        let lastItem2 = this.findLast(lastItem.parentId, data)
        lastIds.push(...lastItem2)
      }
      return lastIds
    },
    // 显示隐藏子集
    toggleChildren (item) {
      item.expand = !item.expand
      let children
      if (item.expand) {
        children = this.findOneChild(item.value)
      } else {
        children = this.findChild(item.value)
      }
      const ids = children.map(item => {
        return item.value
      })
      const data = this.getCurData()
      data.forEach(i => {
        if (ids.includes(i.value)) {
          i.show = item.expand
          // i.expand = item.expand
        }
      })
    },
    // 找到下面一级的子集id
    findOneChild (id) {
      const data = this.getCurData()
      let children = data.filter((item) => {
        return item.parentId === id
      })
      let child = this.findExpandChild(children)
      children = children.concat(child)
      return children
    },
    // 找到展开的子级
    findExpandChild (arr) {
      let result = []
      arr.forEach(item => {
        if (item.expand) {
          let child = this.findOneChild(item.value)
          result = result.concat(child)
        }
      })
      return result
    },
    // 找到下面的所有子集id
    findChild (id) {
      const data = this.getCurData()
      let child = data.filter((item) => {
        return item.parentId === id
      })
      child.forEach(item => {
        if (item.childrenCount > 0) {
          const newArr = this.findChild(item.value)
          child = child.concat(newArr)
        }
      })
      return child
    },
    // 保存
    save () {
      if (!this.isEdit) {
        this.isEdit = true
      } else {
        let menulist = Object.entries(this.Enums.SYS_PERMISSION)
          .map(item => item[1])
        let idArr = this.getSubmitData(menulist)
        console.log(idArr)
      }
    },
    getSubmitData (menulist) {
      let result = []
      let ids = this.getIds()
      let data = this.getCurData()
      for (let key in ids) {
        if (ids[key]) {
          result.push(key)
          let item = data.find(i => {
            return i.value + '' === key
          })
          if (item.type === 'PAGE') {
            menulist.forEach(child => {
              if (child.parentId + '' === key) {
                result.push(child.value + '')
              }
            })
          }
        }
      }
      return result
    },
    // 切换toggle
    changeToggle (item, value) {
      let data = this.getCurData()
      let ids = this.getIds()
      let children
      if (item.parentId === null) {
        children = data.filter(child => child.parentId === item.value)
        children.forEach(child => {
          ids[child.value] = value
        })
      } else {
        let parent = data.find(child => child.value === item.parentId)
        children = data.filter(child => child.parentId === parent.value)
        if (value) {
          ids[parent.value] = value
        } else {
          let isAllFalse = true
          children.forEach(item => {
            if (ids[item.value]) {
              isAllFalse = false
            }
          })
          ids[parent.value] = !isAllFalse
        }
      }
      this.setIds(ids)
    },
    // 获取当前操作数据
    getCurData () {
      let data
      switch (this.tab) {
        case 'pc':
          data = this.dataPC
          break
        case 'mobile':
          data = this.dataPhone
          break
        case 'pad':
          data = this.dataPad
          break
        case 'board':
          data = this.dataBoard
          break
      }
      return data
    },
    setData (value) {
      switch (this.tab) {
        case 'pc':
          this.dataPC = value
          break
        case 'mobile':
          this.dataPhone = value
          break
        case 'pad':
          this.dataPad = value
          break
        case 'board':
          this.dataBoard = value
          break
      }
    },
    setLoading (value) {
      switch (this.tab) {
        case 'pc':
          this.pcLoading = value
          break
        case 'mobile':
          this.phoneLoading = value
          break
        case 'pad':
          this.padLoading = value
          break
        case 'board':
          this.boardLoading = value
          break
      }
    },
    // 设置ids的值
    setIds (ids) {
      switch (this.tab) {
        case 'pc':
          this.idsPC = ids
          break
        case 'mobile':
          this.idsPhone = ids
          break
        case 'pad':
          this.idsPad = ids
          break
        case 'board':
          this.idsBoard = ids
          break
      }
    },
    getIds () {
      let ids
      switch (this.tab) {
        case 'pc':
          ids = this.idsPC
          break
        case 'mobile':
          ids = this.idsPhone
          break
        case 'pad':
          ids = this.idsPad
          break
        case 'board':
          ids = this.idsBoard
          break
      }
      return ids
    }
  },
  components: {
    Unfold
  }
}
</script>

<style scoped lang="stylus">
.base-menu{
  .box {
    display flex
    flex-direction column
    width 100%
    min-width 250px
    border-radius 6px
    overflow hidden
    height 100%

    .box-header {
      flex 40px 0
      padding 0 20px
      line-height 40px
      font-size 18px
      display flex
      align-items center
    }

    &.left {
      .box-content {
        flex 1
        padding-bottom 20px

        .role-item {
          padding-left 30px
          font-size 16px

          &.activated {
            background #cfd6fe
            color $primary
          }

          &:hover {
            background #e8ebff

            /deep/ .q-focus-helper {
              display none
            }
          }
        }

        .q-separator {
          margin-left 20px
          width calc(100% - 40px)
        }
      }
    }

    &.right {
      padding 0 20px
      .box-content {
        display flex
        flex-direction column
        flex 1
        padding-top 20px
        .toolbar{
          flex 36px 0
        }
        .tab-panel{
          flex calc(100vh - 278px) 0
        }
      }
    }
  }
  /deep/ .fold .right-part {
    padding-top 0
  }
}
</style>
<style lang='stylus'>
.base-menu{
  .q-tab-panel{
    padding 0
  }
  .myTable-line{
    margin 20px 0;
    .q-table__middle{
      max-height calc(100vh - 278px);
      height calc(100vh - 278px);
    }
  }
}
</style>
